package cn.kgc.service.impl;

import cn.kgc.client.RestDmCinemaClient;
import cn.kgc.client.RestDmImageClient;
import cn.kgc.client.RestDmItemClient;
import cn.kgc.config.ItemSearchVo;
import cn.kgc.service.ItemSearchService;
import cn.kgc.utils.Constants;
import cn.kgc.utils.DateUtil;
import cn.kgc.utils.EmptyUtils;
import cn.kgc.utils.FileUtils;
import cn.kgc.config.AbstractEsQuery;
import cn.kgc.config.EsUtils;
import cn.kgc.config.ItemEsQuery;
import cn.kgc.config.ItemQuery;
import cn.kgc.dto.Page;
import cn.kgc.pojo.DmCinema;
import cn.kgc.pojo.DmImage;
import cn.kgc.pojo.DmItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import  java.util.*;
@Service
public class ItemSearchServiceImpl implements ItemSearchService {


    @Autowired
    EsUtils esUtils;
    

    Logger logger= LoggerFactory.getLogger(ItemSearchServiceImpl.class);


    @Value("${lastUpdateTimeFile}")
    private String lastUpdateTimeFile;

    @Autowired
    private RestDmItemClient restDmItemClient;

    @Autowired
    private RestDmImageClient restDmImageClient;
    
    @Autowired
    private RestDmCinemaClient restDmCinemaClient;
    
    @Override
    public Page<ItemSearchVo> queryItemList(ItemQuery itemQuery) throws Exception {
        //将itemQuery-----》AbstractEsQuery
        AbstractEsQuery itemEsQuery = new ItemEsQuery();
        if (EmptyUtils.isNotEmpty(itemQuery.getItemTypeId1()) && itemQuery.getItemTypeId1() != 0)
            itemEsQuery.setMatchParams("itemTypeId1", itemQuery.getItemTypeId1());
        if (EmptyUtils.isNotEmpty(itemQuery.getItemTypeId2()) && itemQuery.getItemTypeId2() != 0)
            itemEsQuery.setMatchParams("itemTypeId2", itemQuery.getItemTypeId2());
        if (EmptyUtils.isNotEmpty(itemQuery.getAreaId()) && itemQuery.getAreaId() != 0)
            itemEsQuery.setMatchParams("areaId", itemQuery.getAreaId());
        if (EmptyUtils.isNotEmpty(itemQuery.getKeyword()))
            itemEsQuery.setLikeMatchParams("itemName", itemQuery.getKeyword());
        if (EmptyUtils.isNotEmpty(itemQuery.getStartTime())) {
            Long startTimeLong = DateUtil.parse(itemQuery.getStartTime(), "yyyy-MM-dd").getTime();
            itemEsQuery.setGteParams("startTime", startTimeLong);
        }
        if (EmptyUtils.isNotEmpty(itemQuery.getEndTime())) {
            Long endTimeLong = DateUtil.parse(itemQuery.getEndTime(), "yyyy-MM-dd").getTime();
            itemEsQuery.setLteParams("endTime", endTimeLong);
        }
        if (EmptyUtils.isNotEmpty(itemQuery.getSort())) {
            if (itemQuery.getSort().equals("recommend")) {// 推荐度
                itemEsQuery.setDesc("commentCount");
            } else if (itemQuery.getSort().equals("recentShow")) { // 最近开始
                itemEsQuery.setDesc("startTime");
            } else if (itemQuery.getSort().equals("recentSell")) { // 最新上架
                itemEsQuery.setDesc("startTimeLong");
            }
        }
        itemEsQuery.setPageNo(itemQuery.getCurrentPage());
        itemEsQuery.setPageSize(itemQuery.getPageSize());


        //调用EsUtils
        return esUtils.queryPage(itemEsQuery);
    }


    public String getLastUpdateTime() throws IOException {
        //创建文件 E:/updatetime.txt
        FileUtils.createIfNotExist(lastUpdateTimeFile);
        //读取文件
        return FileUtils.readFileByLine(lastUpdateTimeFile);
    }

    /**
     * 周期执行
     * @throws Exception
     */
    @Override
    @Scheduled(cron = "0 0/1 * * * ?")
    public void importItemList() throws Exception {
       System.out.println("update es @ " + Calendar.getInstance());
       Map<String, Object> params = new HashMap<>();
       //获取上一次数据同步的时间（es 和mysql 实现数据同步的时间，）
        //如果没有这个说明，之前没导入过数据，要实现一次全量更新
        //如果有这个时间，获取数据库晚于，大于这个简时间数据找出来，对es增量更新
        String lastUpdateTime = getLastUpdateTime();
        if (EmptyUtils.isNotEmpty(lastUpdateTime)) {
            //2022-9-22 16:41   null
            params.put("lastUpdatedTime", lastUpdateTime);
        }

        //2。全部数据，增量数据
        // List<DmItem> dmItemList  params为null,则的获取所有的节目 全量更新
        //List<DmItem> dmItemList  params为lastUpdatedTime的时候，找出修改时间>上一次同步时间的数据进行增量更新
        List<DmItem> dmItemList = restDmItemClient.getDmItemListByMap(params);

        List<ItemSearchVo> itemSearchVoList = new ArrayList<>();
        //mysql 数据库中的商品DmItem 联通影院，及图片数据封装到  ItemSearchVo---List----》es
                if (EmptyUtils.isNotEmpty(dmItemList)) {
                    for (DmItem dmItem : dmItemList) {
                        ItemSearchVo itemSearchVo = new ItemSearchVo();
                        BeanUtils.copyProperties(dmItem, itemSearchVo);

                       List<DmImage> dmImages = restDmImageClient.getDmImage_DefaultImage(dmItem.getId(),
                              Constants.Image.ImageType.normal, Constants.Image.ImageCategory.item);

                        itemSearchVo.setImgUrl(EmptyUtils.isEmpty(dmImages)?null:dmImages.get(0).getImgUrl());

                        itemSearchVo.setItemTypeId1(dmItem.getItemType1Id());
                itemSearchVo.setItemTypeId2(dmItem.getItemType2Id());
                itemSearchVo.setStartTime(DateUtil.format(dmItem.getStartTime()));
                itemSearchVo.setEndTime(DateUtil.format(dmItem.getEndTime()));

                DmCinema dmCinema = restDmCinemaClient.getDmCinemaById(dmItem.getCinemaId());
                if(dmCinema!=null){
                itemSearchVo.setAreaId(dmCinema.getAreaId());
                itemSearchVo.setAddress(dmCinema.getAddress());
                itemSearchVo.setAreaName(dmCinema.getAreaName());
                }
//                itemSearchVo.setCreatedTimeLong(dmItem.getCreatedTime().getTime());
//                itemSearchVo.setCreatedTime(DateUtil.format(dmItem.getCreatedTime()));
//                itemSearchVo.setStartTimeLong(dmItem.getStartTime().getTime());
//                itemSearchVo.setEndTimeLong(dmItem.getEndTime().getTime());
//                itemSearchVo.setCommentCount(dmItem.getCommentCount());

                itemSearchVoList.add(itemSearchVo);
            }
        }
        System.out.println("+++++++++++++++++"+DateUtil.format(new Date())+"更新了"
                +itemSearchVoList.size()+"数据+++++++++++++++++++++");
        lastUpdateTime = DateUtil.format(new Date());
        FileUtils.writeInFile(lastUpdateTimeFile, lastUpdateTime);

        if (EmptyUtils.isNotEmpty(itemSearchVoList)) {

            //获取到的集合数据放入es中
            esUtils.addBatchEsModule(itemSearchVoList);
        }
    }



//    @Scheduled(cron = "0/1 * * * * ?")
//    public void time(){
//        System.out.println(new Date());
//    }

}
